#include "function.h"
#define IPADDR "127.0.0.1" 
#define PORT 8887


int recvn(int netFd, void* pstart, int len)
{
    int total = 0;
    int ret;
    char *p = (char*)pstart;
    while(total < len)
    {
        ret = recv(netFd, p + total, len - total, 0);
        total += ret;
    }
    return 0;
}

int recvFile(int netFd)
{
    train_t t;
    bzero(&t, sizeof(t));
    recvn(netFd, t.date, t.length);
    int fd = open(t.date, O_WRONLY | O_CREAT, 0666);
    ERROR_CHECK(fd, -1, "open");
    while(1)
    {
        bzero(&t, sizeof(t));
        recvn(netFd, &t.length, sizeof(int));
        if(0 == t.length) break;
        recvn(netFd, t.date, t.length);
        write(fd, t.date, t.length);
    }
    close(fd);
    return 0;
}
        

int main(){
   // ARGS_CHECK(argc, 2);
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sfd, -1, "socket");
    struct sockaddr_in serAddr;
    memset(&serAddr, 0, sizeof(serAddr));
    serAddr.sin_family = AF_INET;
    serAddr.sin_addr.s_addr = inet_addr(IPADDR);
    serAddr.sin_port = htons(PORT);
    int ret = connect(sfd, (struct sockaddr*)&serAddr, sizeof(serAddr));
    ERROR_CHECK(ret, -1, "connect");
    char buf[64] = {0};
    fd_set rdset;
    LoginInterface();
    int closeflag = 0;
    while(1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(sfd, &rdset);
        struct timeval cltime = {60,0};
        int retval=0;
        retval=select(sfd + 1, &rdset, NULL, NULL, &cltime);
        if(retval==0)
        {
            break;
        }
        if(FD_ISSET(STDIN_FILENO, &rdset))
        {
            memset(buf, 0, sizeof(buf));
            ret = read(STDIN_FILENO, buf, sizeof(buf));
            if(ret == 0) break;
            send(sfd, buf, strlen(buf) - 1, 0);
            readorder(buf,ret,&closeflag,sfd);
        }
        else if(FD_ISSET(sfd, &rdset))
        {
            if(closeflag){
                continue;
            }
            memset(buf, 0, sizeof(buf));
            ret = recv(sfd, buf, sizeof(buf), 0);
            //recvFile(sfd);//------------
            if(ret == 0) break;
            printf("%s\n", buf);
        }
    }
    close(sfd);
    return 0;
}
